/**
 * ExportTaskListPage
 * 数据字典导出列表页面
 * Features: 任务列表、创建导出、下载文件、归档重试
 */

import React, { useState } from 'react'
import { Card, Table, Button, Space, Tag, Modal, Form, Select} from 'antd'
import { PlusOutlined, DownloadOutlined, RedoOutlined, FileExcelOutlined, FilePdfOutlined, FileMarkdownOutlined, FileTextOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { useExportTaskList, useCreateExportTask, useDownloadExportFile, useRetryArchive } from '@/hooks/useExportTask'
import { useDataSourceList } from '@/hooks/useDataSource'
import type { ExportTask, ExportTaskCreateRequest } from '@/services/models/types'
import { ExportFormat, ExportStatus } from '@/services/models/types'

// 导出格式图标映射
const FORMAT_ICONS: Record<ExportFormat, React.ReactNode> = {
  [ExportFormat.EXCEL]: <FileExcelOutlined style={{ color: '#52c41a' }} />,
  [ExportFormat.PDF]: <FilePdfOutlined style={{ color: '#ff4d4f' }} />,
  [ExportFormat.MARKDOWN]: <FileMarkdownOutlined style={{ color: '#1890ff' }} />,
  [ExportFormat.HTML]: <FileTextOutlined style={{ color: '#faad14' }} />,
}

// 导出状态标签配置
const STATUS_TAG_CONFIG: Record<ExportStatus, { color: string; text: string }> = {
  [ExportStatus.PENDING]: { color: 'default', text: '等待中' },
  [ExportStatus.RUNNING]: { color: 'processing', text: '生成中' },
  [ExportStatus.SUCCESS]: { color: 'success', text: '成功' },
  [ExportStatus.PARTIAL_SUCCESS]: { color: 'warning', text: '部分成功' },
  [ExportStatus.FAILED]: { color: 'error', text: '失败' },
}


export const ExportTaskListPage: React.FC = () => {
  const [pagination, setPagination] = useState({ page: 0, size: 10 })
  const [modalVisible, setModalVisible] = useState(false)
  const [form] = Form.useForm()

  // 查询导出任务列表
  const { data: exportData, isLoading: exportLoading } = useExportTaskList(pagination)

  // 查询数据源列表(用于创建导出任务)
  const { data: datasourceData } = useDataSourceList({ page: 0, size: 100 })

  // 创建导出任务
  const createMutation = useCreateExportTask()

  // 下载文件
  const downloadMutation = useDownloadExportFile()

  // 重试归档
  const retryArchiveMutation = useRetryArchive()

  // 表格列定义
  const columns: ColumnsType<ExportTask> = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '数据源',
      dataIndex: 'datasourceName',
      width: 150,
    },
    {
      title: '格式',
      dataIndex: 'format',
      width: 100,
      render: (format: ExportFormat) => {
        if (!format) return <span>-</span>
        return (
          <Space>
            {FORMAT_ICONS[format]}
            <span>{format.toUpperCase()}</span>
          </Space>
        )
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      render: (status: ExportStatus) => {
        const config = STATUS_TAG_CONFIG[status]
        return <Tag color={config.color}>{config.text}</Tag>
      },
    },
    {
      title: '归档状态',
      dataIndex: 'isArchived',
      width: 120,
      render: (isArchived: boolean) => (
        <Tag color={isArchived ? 'success' : 'default'}>
          {isArchived ? '已归档' : '未归档'}
        </Tag>
      ),
    },
    {
      title: '文件大小',
      dataIndex: 'fileSizeFormatted',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          {record.status === ExportStatus.SUCCESS && (
            <Button
              type="link"
              icon={<DownloadOutlined />}
              onClick={() => handleDownload(record.id)}
              loading={downloadMutation.isPending}
            >
              下载
            </Button>
          )}
          {!record.isArchived && record.status === ExportStatus.SUCCESS && (
            <Button
              type="link"
              danger
              icon={<RedoOutlined />}
              onClick={() => handleRetryArchive(record.id)}
              loading={retryArchiveMutation.isPending}
            >
              重试归档
            </Button>
          )}
          
        </Space>
      ),
    },
  ]

  // 创建导出任务
  const handleCreateExport = async () => {
    try {
      const values = await form.validateFields()
      const request: ExportTaskCreateRequest = {
        datasourceId: values.datasourceId,
        format: values.exportFormat,
      }
      await createMutation.mutateAsync(request)
      setModalVisible(false)
      form.resetFields()
    } catch (error) {
      // 表单验证失败或创建失败,已在mutation中处理错误提示
    }
  }

  // 下载文件
  const handleDownload = async (id: number) => {
    await downloadMutation.mutateAsync(id)
  }

  // 重试归档
  const handleRetryArchive = async (id: number) => {
    await retryArchiveMutation.mutateAsync(id)
  }

  return (
    <div className="p-6">
      <Card
        title="数据字典导出"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setModalVisible(true)}
          >
            创建导出任务
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={exportData || []}
          rowKey="id"
          loading={exportLoading}
          pagination={{
            current: pagination.page + 1,
            pageSize: pagination.size,
            total: exportData?.length || 0,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => setPagination({ page: page - 1, size }),
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建导出任务弹窗 */}
      <Modal
        title="创建导出任务"
        open={modalVisible}
        onOk={handleCreateExport}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
        }}
        confirmLoading={createMutation.isPending}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            exportFormat: ExportFormat.EXCEL,
          }}
        >
          <Form.Item
            label="选择数据源"
            name="datasourceId"
            rules={[{ required: true, message: '请选择数据源' }]}
          >
            <Select
              placeholder="请选择要导出的数据源"
              showSearch
              optionFilterProp="children"
            >
              {datasourceData?.content?.map((ds) => (
                <Select.Option key={ds.id} value={ds.id}>
                  {ds.name} ({ds.dbType})
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="导出格式"
            name="exportFormat"
            rules={[{ required: true, message: '请选择导出格式' }]}
          >
            <Select>
              <Select.Option value={ExportFormat.EXCEL}>
                <Space>
                  {FORMAT_ICONS[ExportFormat.EXCEL]}
                  Excel (.xlsx)
                </Space>
              </Select.Option>
              <Select.Option value={ExportFormat.PDF}>
                <Space>
                  {FORMAT_ICONS[ExportFormat.PDF]}
                  PDF (.pdf)
                </Space>
              </Select.Option>
              <Select.Option value={ExportFormat.MARKDOWN}>
                <Space>
                  {FORMAT_ICONS[ExportFormat.MARKDOWN]}
                  Markdown (.md)
                </Space>
              </Select.Option>
              <Select.Option value={ExportFormat.HTML}>
                <Space>
                  {FORMAT_ICONS[ExportFormat.HTML]}
                  HTML (.html)
                </Space>
              </Select.Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <div className="text-gray-500 text-sm">
              <p>• 导出任务将在后台执行</p>
              <p>• 导出完成后可在列表中下载文件</p>
              <p>• 文件会自动上传到MinIO归档(如果配置)</p>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default ExportTaskListPage
